import base64
import datetime
import urllib
from typing import Union

from Crypto.Cipher import AES

from base.connection import get_db_session
from common.definition import ret_msg, OrderType, PayStatus


class GiftHelper(object):
    def __init__(self):
        pass

    @staticmethod
    def encrypt_order_id(order_id: str) -> bytes:
        key = str.encode('dwsoft1111111111')
        mode = AES.MODE_CFB
        iv = key
        encryptor = AES.new(key, mode, iv)

        # aes加密
        encrypt_order_id = encryptor.encrypt(str.encode(order_id))
        encrypt_order_id = base64.b64encode(encrypt_order_id).decode()
        encrypt_order_id = urllib.request.quote(encrypt_order_id)
        return encrypt_order_id

    @staticmethod
    def decrypt_order_id(order_id: bytes) -> str:
        # url解码
        order_id = urllib.request.unquote(order_id)
        order_id = base64.b64decode(order_id)

        key = str.encode('dwsoft1111111111')
        mode = AES.MODE_CFB
        iv = key
        encryptor = AES.new(key, mode, iv)
        decrypt_order_id = encryptor.decrypt(order_id).decode()
        return decrypt_order_id

    @staticmethod
    def check_order(order_id: str):
        ret = ret_msg(is_dumps=False)

        class GoodsOrder(object):
            pass

        session = get_db_session([
            {"db_table": "sdet_order", "model": GoodsOrder},
        ])
        order = session.query(GoodsOrder).filter_by(sdef_order_id=order_id).first()
        if not order:
            ret["code"] = -1
            ret["msg"] = "订单不存在"
            session.close()
            return ret

        # 检查订单类型
        if order.sdef_order_type != OrderType.GIFT:
            ret["code"] = -1
            ret["msg"] = "非礼品订单"
            session.close()
            return ret

        # 检查是否已支付
        if order.sdef_order_pay_status != PayStatus.SUCCESS:
            ret["code"] = -1
            ret["msg"] = "订单未支付或已退款"
            session.close()
            return ret
        # 检查订单是否已签收
        if order.sdef_order_address_id:
            ret["code"] = -1
            ret["msg"] = "已确认"
            session.close()
            return ret

        # 检查是否已超时(48小时超时时间)
        now = datetime.datetime.now()
        create_time = order.sdef_order_create_time
        ts = now - create_time
        if ts.seconds > 172800:
            ret["code"] = -1
            ret["msg"] = "订单已失效"
            session.close()
            return ret

        return ret


if __name__ == "__main__":
    # r = GiftHelper.decrypt_order_id("HiP/0sUxqrk%3D")
    # print(r)
    pass
